package com.xquant.trade.trade.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageInfo;
import com.xquant.common.core.utils.PageUtils;
import com.xquant.common.core.web.controller.BaseController;
import com.xquant.common.core.web.page.TableDataInfo;
import com.xquant.common.security.annotation.RequiresPermissions;
import com.xquant.common.security.utils.SecurityUtils;
import com.xquant.trade.sysconfig.service.ISystemConfigService;
import com.xquant.trade.trade.entity.Trade;
import com.xquant.trade.trade.mapper.TradeMapper;
import com.xquant.trade.trade.service.impl.DurationServiceImpl;
import com.xquant.trade.utils.CommResponse;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * newCloud
 * 存续期管理
 */
@RestController
@RequestMapping("durationController")
public class DurationController extends BaseController {

    @Autowired
    private DurationServiceImpl durationService;

    @Autowired
    private TradeMapper tradeMapper;

    @Autowired
    private ISystemConfigService systemConfigService;


    /**
     * newCloud controller 查询提醒日历
     *
     * @param params
     * @return
     */
    @RequestMapping(value = "/queryAllTradeRemind.action")
    List queryTradeRemind(@RequestParam Map params) {
        List<Map> list = durationService.queryAllTradeRemind();
        list.forEach(item -> {
            item.put("id", RandomUtil.randomInt());
            item.put("ad", true);
            item.put("rem", "15");
            item.put("loc", "15");
        });
        return list;
    }

    /**
     * 查询一个月的提醒日历
     *
     * @param params
     * @return
     */
    @RequestMapping(value = "/query30DaysTradeRemind.action")
    List query30DaysTradeTRemind(@RequestParam Map params) {
        //查询当天的前一个交易日
        Integer calDayDiff = durationService.queryLastCalDayDiff(new Date());
        params.put("calDayDiff", calDayDiff);
        params.put("userId", SecurityUtils.getUserId());
        List<Map> list = durationService.query30DaysTradeRemind(params);
        list.forEach(item -> {
            item.put("id", RandomUtil.randomInt());
            item.put("ad", true);
            item.put("rem", "15");
            item.put("loc", "15");
        });
        return list;
    }


    /**
     * 查询当天到期的场外期权交易列表
     */
    @RequestMapping(value = "/queryTodayTrade4OtcOptionByPage.action")
    TableDataInfo queryTodayTrade4OtcOptionByPage(@RequestBody Map map) {
        startPage();
        if (StrUtil.isNotBlank(MapUtils.getString(map, "iCodes"))) {
            map.put("iCodes", JSONUtil.parseArray(MapUtils.getString(map, "iCodes")).toArray(String.class));
        }
        map.put("userId", SecurityUtils.getUserId());
        String tradeTypes = MapUtils.getString(map, "tradeTypes");
        if (StringUtils.isNotEmpty(tradeTypes)) {
            map.put("tradeTypes", tradeTypes.split(","));
        }
        String optionType = MapUtils.getString(map, "optionType");

        PageUtils.startPage(MapUtils.getIntValue(map,"pageNum"),MapUtils.getIntValue(map,"pageSize"),"TRADE_ID asc");
        List<Trade> list = durationService.queryTodayTrade4OtcOptionByPage(map);
        return getDataTable(list);
    }


    /**
     * 查询日历配置的日期
     *
     * @param params
     * @return
     */
    @RequestMapping(value = "/queryTradeCalendarDates.action")
    List queryTradeCalendarDates(@RequestParam Map params) {
        List<Map> list = durationService.queryTradeCalendarDates(params);
        return list;
    }

    /**
     * 查询日历配置的日历类型
     *
     * @param params
     * @return
     */
    @RequestMapping(value = "/queryTradeCalendar.action")
    Object queryTradeCalendar(@RequestParam Map params) {
        List<Map> list = durationService.queryTradeCalendar(params);
        return list;
    }

    /**
     * 修改日历配置
     *
     * @param params
     * @return
     */
    @RequestMapping(value = "/updateTradeCalendarDates.action")
    CommResponse updateTradeCalendarDates(@RequestParam Map params) {
        durationService.updateTradeCalendarDates(params);
        return CommResponse.success("修改日历成功");
    }

    /**
     * 批量修改日历配置
     *
     * @param params
     * @return
     */
    @RequestMapping(value = "/updateTradeCalendarDatesByYear.action")
    CommResponse updateTradeCalendarDatesByYear(@RequestParam Map params) {
        durationService.updateTradeCalendarDatesByYear(params);
        return CommResponse.success("修改日历成功");
    }

    /**
     * 修改日历配置，如果不存在，就新增
     *
     * @param params
     * @return
     */

    @RequiresPermissions("trade:tradecalendar:setall")
    @RequestMapping(value = "/insertTCalendarDatesIfNotExist.action")
    CommResponse insertTCalendarDatesIfNotExist(@RequestParam Map params) {
        durationService.insertTCalendarDatesIfNotExist(params);
        return CommResponse.success("修改日历成功");
    }

    /**
     * 批量修改日历配置，如果不存在，就新增
     *
     * @param params
     * @return
     */
    @RequiresPermissions("trade:tradecalendar:setall")
    @RequestMapping(value = "/insertTCalendarDatesIfNotExistByYear.action")
    CommResponse insertTCalendarDatesIfNotExistByYear(@RequestBody Map params) {

        durationService.insertTCalendarDatesIfNotExistByYear(params);
        return CommResponse.success("修改日历成功");
    }


    /**
     * 查询到期合约
     */
    @RequestMapping(value = "/queryExpireContract.action")
    PageInfo<Map> queryExpireContract(@RequestParam Map map) {
        map.put("xExpireMaturityDay", systemConfigService.selectConfigByKey("xExpireMaturityDay"));
        map.put("userId", SecurityUtils.getUserId());
        return durationService.queryExpireContract(map);
    }

    /**
     * 计算场外期权交易列表
     */
    @RequestMapping(value = "/calcTrade4OtcOptionByPage.action")
    @PreAuthorize("@ss.hasPermi('trade:tradebalance:calc')")
    CommResponse calcTrade4OtcOptionByPage(@RequestParam Map map) throws ParseException {
        map.put("userId", SecurityUtils.getUserId());
        String tradeTypes = MapUtils.getString(map, "tradeTypes");
        if (StringUtils.isNotEmpty(tradeTypes)) {
            map.put("tradeTypes", tradeTypes.split(","));
        }

        String instruments = MapUtils.getString(map, "instruments");
        if (org.apache.commons.lang.StringUtils.isNotEmpty(instruments)) {
            map.put("instruments", instruments.split("\\|"));
        }
        String accIds = MapUtils.getString(map, "accIds");
        if (org.apache.commons.lang.StringUtils.isNotEmpty(accIds)) {
            map.put("accIds", accIds.split(","));
        }
        String partyIds = MapUtils.getString(map, "partyIds");
        if (org.apache.commons.lang.StringUtils.isNotEmpty(partyIds)) {
            map.put("partyIds", partyIds.split(","));
        }

        if (StrUtil.isNotBlank(MapUtils.getString(map, "duEventStatus"))) {
            if (JSONUtil.parseArray(MapUtils.getString(map, "duEventStatus")).size() > 0) {
                map.put("duEventStatus", JSONUtil.parseArray(MapUtils.getString(map, "duEventStatus")).toArray(String.class));
            } else {
                map.put("duEventStatus", null);
            }
        }

        if (StrUtil.isNotBlank(MapUtils.getString(map, "productTypes"))) {
            if (JSONUtil.parseArray(MapUtils.getString(map, "productTypes")).size() > 0) {
                map.put("productTypes", JSONUtil.parseArray(MapUtils.getString(map, "productTypes")).toArray(String.class));
            }else {
                map.put("productTypes", null);
            }
        }

        if (StrUtil.isNotBlank(MapUtils.getString(map, "tradeIds"))) {
            if (JSONUtil.parseArray(MapUtils.getString(map, "tradeIds")).size() > 0) {
                map.put("tradeIds", JSONUtil.parseArray(MapUtils.getString(map, "tradeIds")).toArray(String.class));
            }
        }

        if (StrUtil.isNotBlank(MapUtils.getString(map, "iCodes"))) {
            if (JSONUtil.parseArray(MapUtils.getString(map, "iCodes")).size() > 0) {
                map.put("iCodes", JSONUtil.parseArray(MapUtils.getString(map, "iCodes")).toArray(String.class));
            }
        }

        durationService.calcTrade4OtcOptionByPage(map);
        return CommResponse.success();
    }
}
